<template>
  <el-dialog
    width="1200px"
    :close-on-click-modal="false"
    :title="title"
    :visible.sync="visible"
    append-to-body
    @close="close"
  >
    <layout :search="false">
      <template slot="operation">
        <div class="operation-left">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="add()"
            class="mr10"
          >添加派工单</el-button>
        </div>
      </template>

      <template slot="content">
        <el-form class="bg-white" ref="form">
          <!--新增派工单  -->
          <div :class="d2" class="h-60vh">
            <el-row>
              <el-form-item
                label="派工单数量"
                class="w-100percent bold bg-lightGray mb0"
              >
                <el-input-number
                  v-model="bb.number"
                  placeholder="数量"
                  size="small"
                  class="w100 ml20"
                  :min="0"
                  :max="200"
                ></el-input-number>

                <el-select
                  v-model="bb.versionId"
                  filterable
                  class="w180 ml20"
                  placeholder="选择工艺版本"
                  @change="changeVersion"
                >
                  <template v-for="option in this.processDetail">
                    <el-option :label="option.versionName" :value="option.versionId"></el-option>
                  </template>
                </el-select>
                <el-button
                  type="text"
                  icon="el-icon-plus"
                  :disabled="addEquipment"
                  @click="addRow"
                >添加设备</el-button>
                <el-button
                  type="text"
                  icon="el-icon-plus"
                  :disabled="addPerson"
                  @click="addRow2"
                >添加指派人</el-button>
                <el-button type="text" icon="el-icon-check" @click="save">提交</el-button>
              </el-form-item>
            </el-row>

            <el-table
              ref="articleTable"
              border
              stripe
              :data="addproduct"
              row-key="tid"
              default-expand-all
              :span-method="merge"
              @selection-change="addSelection"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            >
              <el-table-column type="selection" fixed="left" width="40"></el-table-column>
              <el-table-column prop="sequenceNumber" label="工序号" align="right" width="70"></el-table-column>
              <el-table-column prop="processName" label="工序名称" align="center" width="100"></el-table-column>
              <el-table-column prop="department" label="部门" align="center" width="80"></el-table-column>
              <el-table-column prop="supplier" label="供应商" align="center" width="80"></el-table-column>
              <el-table-column prop="totalNumber" label="工序数量" align="center" width="80">
                <template slot-scope="scope">
                    <input class="input1" v-if="scope.row.department=='加工'||scope.row.equipment"  v-model="scope.row.totalNumber"></input>
                </template>
              </el-table-column>
              <el-table-column prop="equipment" label="设备" align="center" width="130">
                <template slot-scope="scope" v-if="scope.row.processName!='完工'">
                  <el-select
                    v-if="!scope.row.sequenceNumber&&!scope.row.workerName"
                    v-model="scope.row.equipment"
                    filterable
                  >
                    <template v-for="option in addproduct.children">
                      <el-option :key="option.id" :label="option.equipment" :value="option.id"></el-option>
                    </template>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="workerName" label="指派人" align="center" width="100">
                <template slot-scope="scope">
                  <el-select
                    v-if="!scope.row.sequenceNumber&&!scope.row.equipment"
                    v-model="scope.row.workerName"
                    filterable
                  >
                    <template v-for="option in addproduct.children">
                      <el-option
                        v-if="addproduct.children.children"
                        :key="option.workerId"
                        :label="option.workerName"
                        :value="option.workerId"
                      ></el-option>
                    </template>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="workerNumber" label="派工数量" align="center" width="80">
                <template slot-scope="scope">
                   <input class="input1" v-if="scope.row.workerName" v-model="scope.row.number" ></input> 
                </template>
              </el-table-column>
              <el-table-column prop="single" label="单机" align="center" min-width="80">
                <template slot-scope="scope" v-if="scope.row.processName!='完工'">
                  <el-switch
                    v-if="scope.row.department=='加工'"
                    v-model="scope.row.single"
                    active-color="#13ce66"
                    disabled
                  ></el-switch>
                  <!--      <el-input v-model="scope.row.remark"></el-input>-->
                </template>
              </el-table-column>
              <el-table-column prop="quotaHour" label="定额工时" align="center" width="80"></el-table-column>
              <el-table-column prop="debugHour" label="调试工时" align="center" min-width="80"></el-table-column>
              <el-table-column label="操作" fixed="right" align="center" width="110">
                <template slot-scope="scope">
                  <el-tooltip content="删除指派人" placement="top-end" effect="light">
                    <el-button
                      @click.native.prevent="deleteRow(scope.row.tid, addproduct)"
                      type="text"
                      icon="el-icon-delete"
                      size="small"
                    ></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="h-70vh overflow-y-scroll">
            <hr />
            <el-form-item
              class="w-100percent bold bg-lightGray mb0"
            >派工单列表</el-form-item>
            <el-collapse accordion @change="activeChange" v-model="activeCollapseData">
              <template v-for="item in  this.dispatchList">
                <el-collapse-item :name="item.id">
                  <template slot="title">
                    <span class="fontSize14 bold">派工单号：</span>
                    {{item.dispatchNumber}}
                    <span
                      class="pl15 fontSize14 bold"
                    >派工数量：</span>
                    {{item.number}}
                    <span
                      class="pl15 fontSize14 bold"
                    >派工时间：</span>
                    {{item.dispatchTime}}
                    <span
                      class="pl15 fontSize14 bold"
                    >完工数量：</span>
                    {{item.finishNumber}}
                    <span
                      class="pl15 fontSize14 bold"
                    >完工时间：</span>
                    {{item.finishTime}}
                    <span
                      class="pl15 fontSize14 bold"
                    >状态：</span>
                    {{item.state}}
                  </template>
                  <el-form class="bg-white p-10h-90percent">
                    <el-row>
                      <el-form-item
                        label="派工单"
                        class="w-100percent bold bg-lightGray mb0"
                      >
                        <el-button
                          type="text"
                          size="small"
                          class="w50"
                          icon="el-icon-edit"
                          default-expand-all
                          :disabled="item.state!='工序异常'"
                          @click="editChange(item.id,item.versionId,item.producingId)"
                        >{{edit_title}}</el-button>

                        <el-button
                          type="text"
                          size="small"
                          class="w100"
                          icon="el-icon-s-claim"
                          :disabled="singleShow||StateShow"
                          @click="review()"
                        >单双机审核</el-button>
                        <el-button
                          type="text"
                          size="small"
                          class="w80"
                          icon="el-icon-check"
                          :disabled="StateShow"
                          @click="success(item.id)"
                        >完工确认</el-button>
                        <el-button
                          type="text"
                          size="small"
                          class="w50"
                          icon="el-icon-warning-outline"
                          @click="stop(item.id)"
                          :disabled="StateShow"
                        >终止</el-button>
                        <el-button
                          type="text"
                          size="small"
                          @click="qr(item.dispatchFormId,item.dispatchFormNumber)"
                          disabled
                        >生成二维码</el-button>
                        <QR ref="qr"></QR>
                      </el-form-item>
                    </el-row>

                    <el-table
                      height="50vh"
                      border
                      stripe
                      class="mb10"
                      :data="product"
                      row-key="sid"
                      :span-method="merge"
                      @selection-change="Selection"
                      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                    >
                      <el-table-column type="selection" fixed="left" width="40"></el-table-column>
                      <el-table-column prop="sequenceNumber" label="工序号" align="right" width="70"></el-table-column>
                      <el-table-column prop="processName" label="工序名称" align="center" width="100"></el-table-column>
                      <el-table-column prop="department" label="部门" align="center" width="100"></el-table-column>
                      <el-table-column prop="totalNumber" label="工序数量" align="center" width="100">
                        <template  slot-scope="scope">
                            <input v-if="scope.row.state=='未开始'&&item.state=='工序异常'" class="input1" :disabled="!editable"  v-model="scope.row.totalNumber"></input>  
                            <span v-else> {{scope.row.totalNumber}}</span>
                        </template>

                      </el-table-column>
                      <el-table-column prop="equipment" label="设备" align="center" width="75"></el-table-column>
                      <el-table-column prop="workerName" label="指派(完工)人" align="center" width="125"></el-table-column>
                      <el-table-column
                        prop="workerNumber"
                        label="派工(完工)数量"
                        align="center"
                        width="125"
                      >
                        <template v-if="scope.row.workerName" slot-scope="scope">
                           <input class="input1" v-if="scope.row.state!='质检完成'" :disabled="!editable"  v-model="scope.row.workerNumber"></input>
                            <span v-else> {{scope.row.workerNumber}}</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="single" label="单双机" align="center" width="75">
                        <template slot-scope="scope">
                          <el-switch disabled v-model="scope.row.rem" active-color="#13ce66"></el-switch>
                        </template>
                      </el-table-column>
                      <el-table-column prop="quotaHour" label="定额工时" align="center" width="80"></el-table-column>
                      <el-table-column prop="debugHour" label="调试工时" align="center" width="80"></el-table-column>
                      <el-table-column prop="realWorkHour" label="实动工时" align="center" width="80"></el-table-column>
                      <el-table-column prop="numberQualified" label="合格" align="center" width="80"></el-table-column>
                      <el-table-column prop="numberDebug" label="调试合格" align="center" width="80"></el-table-column>
                      <el-table-column prop="numberPending" label="待处理" align="center" width="80"></el-table-column>
                      <el-table-column
                        prop="numberWasteIndustrial"
                        label="工废"
                        align="center"
                        width="80"
                      ></el-table-column>
                      <el-table-column
                        prop="numberWasteMaterial"
                        label="废料"
                        align="center"
                        width="80"
                      ></el-table-column>
                      <el-table-column prop="numberRework" label="返修数量" align="center" width="80"></el-table-column>
                      <el-table-column prop="state" label="质检确认" align="center" min-width="80"></el-table-column>
                    </el-table>
                  </el-form>
                </el-collapse-item>
              </template>
            </el-collapse>
          </div>
        </el-form>
      </template>
    </layout>
  </el-dialog>
</template>



<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
import { State, namespace } from 'vuex-class'
import Layout from '@/views/_common/Layout.vue'
import QR from './qr.vue'

const vuexDispatch = namespace('ThreeDispatch')

@Component({
  components: {
    Layout,
    QR
  }
})
export default class DialogDetail extends Vue {
  public $refs!: {
    form: any
    articleTable: any
    qr: any
  }

  @vuexDispatch.State dispatchList: any
  @vuexDispatch.State processDetail: any

  //接口
  @vuexDispatch.Action GET_DETAIL_DISPATCH: any
  @vuexDispatch.Action GET_PV_DISPATCH: any
  @vuexDispatch.Action CREATE_DISPATCH: any
  @vuexDispatch.Action QRCODE_DISPATCH: any
  @vuexDispatch.Action UPDATE_DISPATCH: any
  @vuexDispatch.Action STOP_DISPATCH: any
  @vuexDispatch.Action SINGLE_DISPATCH: any
  @vuexDispatch.Action CONFIRM_DISPATCH: any

  // 当前激活的折叠项
  activeCollapseData: string = ''
  visible: boolean = false
  StateShow: boolean = false //状态决定是否展示按钮
  disable: boolean = true //变更展示
  editable: boolean = false //input
  title: string = '派工'
  pv: boolean = false //派工准备数据获取
  singleShow: boolean = true //单双机审核
  addPerson: boolean = true //添加指派人
  addEquipment: boolean = true //添加设备
  Tid: string = ''
  tid: number = 0
  selectId: string = ''

  d2: string = 'd'
  edit_title: string = '变更'
  equipmentList: any[] = []
  workerList: any[] = []
  basics: any = {
    id: '',
    dispatchNumber: '',
    number: '',
    state: ''
  }
  /*测试css
  dispatchList:any[]=[
    {number:300},
    {number:300},
    {number:300},
    {number:300},
    {number:300},
   
    
  ]
  */
  //新增派工单表格数据
  addproduct: any[] = []
  //已存在派工单数据
  product: any[] = [
    {
      orderNumber: ''
    },
    {
      orderNumber: ''
    },
    {
      orderNumber: ''
    },
    {
      orderNumber: ''
    },
    {
      orderNumber: ''
    },
    {
      orderNumber: ''
    },
    {
      orderNumber: ''
    },
    {
      orderNumber: ''
    },
    {
      orderNumber: ''
    }
  ]

  //添加派工单
  processList: any[] = [
    {
      id: '1',
      totalNumber: '',
      children: [
        {
          children: [
            {
              workerId: '002',
              workerNumber: '100'
            }
          ],
          id: '01'
        }
      ]
    },
    {
      id: '1',
      totalNumber: '',
      children: [
        {
          children: [
            {
              workerId: '002',
              workerNumber: '100'
            }
          ],
          id: '01'
        }
      ]
    },
    {
      id: '1',
      totalNumber: '',
      children: [
        {
          children: [
            {
              workerId: '002',
              workerNumber: '100'
            }
          ],
          id: '01'
        }
      ]
    }
  ]

  //去tid  不需要了 直接把addproduct 移到processlist 上
  changeData(data: any) {
    // console.log('提交处理前', data)
    let count = 1
    let arr = [
      {
        processSequenceId: 0
      }
    ]

    for (let i = 0; i < data.length; i++) {
      if (data[i].department == '采购' || data[i].department == '外协') {
        let obj = {
          processSequenceId: 0,
          processName: '',
          sequenceNumber: 1,
          supplier: '',
          department: '',
          totalNumber: 0
        }
        obj.processSequenceId = data[i].id
        obj.processName = data[i].processName
        obj.sequenceNumber = data[i].sequenceNumber
        obj.supplier = data[i].supplier
        obj.department = data[i].department
        obj.totalNumber = this.bb.number
        arr.push(obj)
      } else if (data[i].processName == '完工') {
        let obj = {
          processSequenceId: 0,
          processName: '',
          sequenceNumber: 1,
          totalNumber: 0
        }
        obj.processSequenceId = data[i].id
        obj.processName = data[i].processName
        obj.sequenceNumber = data[i].sequenceNumber
        obj.totalNumber = this.bb.number
        arr.push(obj)
      } else if (data[i].department == '加工') {
        if (data[i].totalNumber > this.bb.number) {
          //提示数量错误
          this.$alert('请保证每道工序的总数量小于等于派工单的数量！', '操作失败', {
            confirmButtonText: '确定',
            type: 'warning'
          })
          count = 0
          break
        } else {
          let obj = {
            processSequenceId: 0,
            totalNumber: 0,
            children: [
              {
                equipHourId: '测试'
              }
            ]
          }
          let processSequenceId = data[i].id
          let totalNumber = data[i].totalNumber
          obj.processSequenceId = processSequenceId
          obj.totalNumber = Number(totalNumber)
          if (data[i].children) {
            if (data[i].children.length > 0) {
              //设备
              let e = data[i].children
              for (let j = 0; j < e.length; j++) {
                let obje = {
                  equipHourId: '',
                  totalNumber: 0,
                  children: [
                    {
                      workerId: '测试',
                      workerNumber: 0
                    }
                  ]
                }

                let value = e[j].id
                obje.equipHourId = value
                obje.totalNumber = Number(e[j].totalNumber)
                if (obje.totalNumber == 0) {
                  continue
                } else {
                  if (e[j].children) {
                    if (e[j].children.length > 0) {
                      //员工
                      let w = e[j].children
                      for (let z = 0; z < w.length; z++) {
                        let objw = {
                          workerId: '',
                          workerNumber: 0
                        }
                        if (w[z].number == 0) {
                          continue
                        } else {
                          let value1 = w[z].workerId
                          let value2 = w[z].number
                          objw.workerId = value1
                          objw.workerNumber = Number(value2)
                          obje.children.push(objw)
                        }
                      }
                    }
                  }

                  if (obje.children[0].workerId == '测试') {
                    obje.children.splice(0, 1)
                  }
                }
                obj.children.push(obje)
              }
            }
            if (obj.children[0].equipHourId == '测试') {
              obj.children.splice(0, 1)
            }
          } else {
            //delete obj.children
            Vue.delete(obj, 'children')
          }
          arr.push(obj)
        }
      }
    }

    if (count) {
      if (arr[0].processSequenceId === 0) {
        arr.splice(0, 1)
      }
      //调用方法，判断设备数目
      this.processList = arr
      let c = this.Equipment(arr)
      //console.log('chulih', this.processList, c)
      return c
    } else {
      return false
    }
  }

  Equipment(data: any) {
    for (let i = 0; i < data.length; i++) {
      if (data[i].children) {
        let equip = data[i].children
        if (equip.length == 0) {
          this.$alert(i + 1 + '号工序没有指派设备！', '操作失败', {
            confirmButtonText: '确定',
            type: 'warning'
          })
          return false
        } else {
          let sum = 0
          for (let j = 0; j < equip.length; j++) {
            //设备层
            sum = sum + equip[j].totalNumber
          }
          if (sum > data[i].totalNumber) {
            this.$alert(i + 1 + '号工序的设备指派总数大于工序总数量！', '操作失败', {
              confirmButtonText: '确定',
              type: 'warning'
            })
            return false
          } else {
            //指派人数量约束

            for (let j = 0; j < equip.length; j++) {
              //设备层
              if (equip[j].children) {
                let work = equip[j].children
                console.log('logging from young : workerList')
                console.log(work)
                let s = 0
                for (let z = 0; z < work.length; z++) {
                  s = s + work[z].workerNumber
                }
                // console.log('logging from young : totalNumber and dispatchWorkerNumber')
                //  console.log(equip[j].totalNumber)
                // console.log(s)
                if (s == equip[j].totalNumber || s == 0) {
                  continue
                } else {
                  this.$alert(i + 1 + '号工序的指派人总数与设备指派总数量不一致！', '操作失败', {
                    confirmButtonText: '确定',
                    type: 'warning'
                  })
                  return false
                }
              }
            }
          }
        }
      }
    }
    return true
  }

  bb: any = {
    producingId: '',
    number: '',
    versionId: ''
  }
  expList: any[] = [
    {
      processSequenceId: 0,
      totalNumber: 0,
      children: [
        {
          equipHourId: 0,
          children: [
            {
              workerId: 0,
              workerNumber: 0
            }
          ]
        }
      ]
    }
  ]

  add() {
    this.getPv()
  }

  async getPv() {
    //获取数据
    let result = await this.GET_PV_DISPATCH({ producingId: this.selectId })

    //console.log(result,'huoq',this.processDetail)
    if (result) {
      this.d2 = 'd2'
      this.pv = true
      // let addList = this.processDetail.processList
      // console.log('chushishuju ', addList)
      //  this.addTid(addList)
    }
  }

  //折叠面板
  activeData: any = []
  activeChange(id: any) {
    console.log('name', id)
    console.log(this.dispatchList)
    this.d2 = 'd'
    let arr = this.dispatchList
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].id === id) {
        this.activeData = arr[i].processList
        this.product = arr[i].processList
        this.show(this.dispatchList[i])
        this.addSid(this.activeData)
        break
      }
    }
  }
  //选择工艺版本

  changeVersion(data) {
    //  console.log('xuanz',data)
    // console.log('banben', this.product)
    let arr = this.processDetail
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].versionId === data) {
        let data = arr[i].processList
        // console.log(arr[i], arr)
        // console.log('data', data, 'lisat', arr[i])

        this.addTid(data)

        break
      }
    }
  }

  //添加tid  equipmentList workerList
  addTid(data) {
    //给原始数据加tid
    let i
    // console.log('jiatid', data)
    // let arr=[]  //没有设备和指派人的数组
    for (i = 0; i < data.length; i++) {
      //工序加tid
      let obj = data[i] //或者 var obj=new Object();//{}
      let key = 'tid'
      this.tid = this.tid + 1
      obj[key] = this.tid
      //加tot
      let key2 = 'totalNumber'
      obj[key2] = this.bb.number
      //加sigle
      if (data[i].supplier) {
        // let equipment = 'equipment'
        //let values = data[i].supplier
        //obj[equipment] = values
      } else if (data[i].equipmentList.length > 0) {
        //设备层
        let child = data[i].equipmentList
        for (let c = 0; c < child.length; c++) {
          //设备 tid
          let obje = child[c] //或者 var obj=new Object();
          let key = 'tid'
          this.tid = this.tid + 1
          let key2 = 'totalNumber'
          obje[key] = this.tid
          obje[key2] = 0
          if (child[c].workerList) {
            if (child[c].workerList.length > 0) {
              let work = child[c].workerList
              for (let w = 0; w < work.length; w++) {
                //人加 tid
                let objw = work[w] //或者 var obj=new Object();
                let key = 'tid'
                this.tid = this.tid + 1
                objw[key] = this.tid
                let key2 = 'number'
                objw[key2] = '0'
              }
              //把worklist换成children
              let objw = child[c]
              let key = 'children'
              let value = child[c].workerList
              objw[key] = value
              delete child[c].workerList
            }
          }
        }
        let obje = data[i]
        let keys = 'children'
        let values = data[i].equipmentList
        obje[keys] = values
        delete data[i].equipmentList
      }
    }
    // console.log('加完' + data)
    /*
   原始数据tid添加完毕end
   */

    /*
arr不要指派人和设备
*/
    /*
for(let j=0;j<data.length;j++){
   if(data[j].children){
       for(let z=0;z<data[j].children.length;z++){
         delete data[j].children[z]
       }
   }
}
*/
    /*end*/

    this.addproduct = data
  }

  show(data) {
    this.basics.id = data.id
    this.basics.number = data.number
    this.basics.dispatchNumber = data.dispatchNumber
    this.basics.state = data.state
    if (data.state == '已完工') {
      this.StateShow = true
    } else if (data.state == '异常终止') {
      this.StateShow = true
    } else {
      this.StateShow = false
    }

    this.product = data.processList

    this.addSid(this.product)
    this.d2 = 'd'
  }

  addSid(data) {
    // console.log('数据转换，加tid')
    let i
    let sid = this.random(0, 500)
    if (data.length > 0) {
      for (i = 0; i < data.length; i++) {
        //工序加tid
        let obj = data[i] //或者 var obj=new Object();//{}
        let key = 'sid'
        let value = sid++ //++sid
        obj[key] = value
        if (data[i].supplier) {
          let equipment = 'equipment'
          let values = data.supplier
          obj[equipment] = values
        } else if (data[i].children.length > 0) {
          let child = data[i].children

          for (let c = 0; c < child.length; c++) {
            //设备 tid
            let obje = child[c] //或者 var obj=new Object();
            let key = 'sid'
            let value = sid++ //++sid
            obje[key] = value
            //  console.log('有设备')
            if (child[c].children.length) {
              // console.log('有人')
              let work = child[c].children
              for (let w = 0; w < work.length; w++) {
                //人加 tid
                let objw = work[w] //或者 var obj=new Object();
                let key = 'sid'
                let value = sid++ //++sid
                objw[key] = value
              }
            } else {
            }
          }
        } else {
          // console.log('无设备')
        }
      }
      // console.log(data)
    }
  }

  open(id: string, num: number) {
    this.selectId = id
    this.visible = true
    this.bb.number = num
  }
  close() {
    this.activeCollapseData = ''
    this.$refs.form.resetFields()
    //初始化
    this.StateShow = false //状态决定是否展示按钮
    this.disable = true //变更展示
    this.editable = false //input
    this.title = '派工'
    this.pv = false //派工准备数据获取
    this.singleShow = true //单双机审核
    this.addPerson = true //添加指派人
    this.addEquipment = true //添加设备
    this.Tid = ''
    this.tid = 0
    this.selectId = ''

    this.d2 = 'd'

    this.equipmentList = []
    this.workerList = []
    this.basics = {
      id: '',
      dispatchNumber: '',
      number: '',
      state: ''
    }

    //新增派工单表格数据
    this.addproduct = []
    //已存在派工单数据
    this.product = [
      {
        orderNumber: ''
      },
      {
        orderNumber: ''
      },
      {
        orderNumber: ''
      },
      {
        orderNumber: ''
      },
      {
        orderNumber: ''
      },
      {
        orderNumber: ''
      },
      {
        orderNumber: ''
      },
      {
        orderNumber: ''
      },
      {
        orderNumber: ''
      }
    ]

    //添加派工单
    this.processList = [
      {
        id: '1',
        totalNumber: '',
        children: [
          {
            children: [
              {
                workerId: '002',
                workerNumber: '100'
              }
            ],
            id: '01'
          }
        ]
      },
      {
        id: '1',
        totalNumber: '',
        children: [
          {
            children: [
              {
                workerId: '002',
                workerNumber: '100'
              }
            ],
            id: '01'
          }
        ]
      },
      {
        id: '1',
        totalNumber: '',
        children: [
          {
            children: [
              {
                workerId: '002',
                workerNumber: '100'
              }
            ],
            id: '01'
          }
        ]
      }
    ]
    this.visible = false
  }
  stop(data) {
    this.$alert('您确定终止本派工单？', '错误提示', {
      confirmButtonText: '确定',
      type: 'error',
      callback: action => {
        // this.$message({
        //   type: 'info',
        //   message: `action: ${action}`
        // })
        if (action === 'confirm') {
          this.$confirm('请提醒未报验员工提交生产信息，终止后将不可填报，是否继续终止操作?', '操作提示', {
            cancelButtonText: '取消',
            confirmButtonText: '确定',
            type: 'warning'
          })
            .then(() => {
              this.stopDispatch(data)
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消操作'
              })
            })
        }
      }
    })
  }
  async stopDispatch(id) {
    let result = await this.STOP_DISPATCH({ id: id })
    if (result) {
      //更新
      this.GET_DETAIL_DISPATCH({ id: id })
    }
  }

  success(id) {
    this.$confirm('派工单完工确认?', '操作提示', {
      cancelButtonText: '取消',
      confirmButtonText: '确定',
      type: 'warning'
    })
      .then(() => {
        this.CONFIRM_DISPATCH({ id: id })
      })
      .catch(() => {
        this.$message({
          type: 'info',
          message: '已取消确认'
        })
      })
  }
  review() {
    this.$confirm('设计单双机与操作者完成上报不一致，如何计算工时？', '操作提示', {
      cancelButtonText: '单机',
      confirmButtonText: '双机',
      type: 'warning'
    })
      .then(() => {
        this.SINGLE_DISPATCH({ id: this.expList[0].id, single: 'false' })
        /*   this.$alert('已确认按双击计算工时！', '操作成功', {
          confirmButtonText: '确定',
          type: 'success'
        })
        */
      })
      .catch(() => {
        //id是质检记录id
        this.SINGLE_DISPATCH({ id: this.expList[0].id, single: 'true' })
      })
  }

  //变更
  async editChange(id, versionId, producingId) {
    console.log('shuzu ', this.product)

    this.editable = !this.editable
    if (this.editable) {
      this.edit_title = '保存'
    } else {
      this.edit_title = '变更'
    }

    //数据处理start
    let data = [
      //传递的数组
      {
        processSequenceId: -1
      }
    ]
    let stop = 0 //判断数量异常

    let count = 0 //判断后续工序均加入数组
    let totalNumber = 0 //记录异常时的总数量
    for (let i = 0; i < this.product.length; i++) {
      if (this.product[i].state == '工序异常') {
        count = 1
        totalNumber = Number(this.product[i].totalNumber)
      }
      if (count) {
        //工序层
        let obj = {
          processSequenceId: -1,
          totalNumber: -1,
          children: [
            {
              equipHourId: -1
            }
          ]
        }
        if (Number(this.product[i].totalNumber) > totalNumber) {
          this.$alert('请保证未开始工序的总数量小于异常工序的总数量！', '操作失败', {
            confirmButtonText: '确定',
            type: 'warning'
          })
          stop = 1
          break
        }
        obj.processSequenceId = this.product[i].processSequenceId
        obj.totalNumber = Number(this.product[i].totalNumber)
        if (this.product[i].children.length) {
          let equip = this.product[i].children
          for (let j = 0; j < equip.length; j++) {
            //设备层
            let obje = {
              equipHourId: -1,
              children: [{ workerId: -1 }]
            }
            obje.equipHourId = equip[j].equipHourId
            if (equip[j].children.length) {
              //员工层
              let s = 0
              let work = equip[j].children
              for (let w = 0; w < work.length; w++) {
                let objw = {
                  workerId: -1,
                  workerNumber: 0
                }
                if (work[w].workerNumber > 0) {
                  objw.workerId = work[w].workerId
                  objw.workerNumber = Number(work[w].workerNumber)
                  s = s + objw.workerNumber
                  obje.children.push(objw)
                }
                if (s > obj.totalNumber) {
                  this.$alert('请保证指派总数量小于等于工序的总数量！', '操作失败', {
                    confirmButtonText: '确定',
                    type: 'warning'
                  })
                  stop = 1
                  break
                }
              }
            }
            if (stop) {
              break
            }
            if (obje.children[0].workerId == -1) {
              obje.children.splice(0, 1)
            }
            obj.children.push(obje)
          }
        }
        if (stop) {
          break
        }
        if (obj.children[0].equipHourId == -1) {
          obj.children.splice(0, 1)
        }
        data.push(obj)
        if (data[0].processSequenceId == -1) {
          data.splice(0, 1)
        }
      }
    }

    //数据处理 end
    if (!stop) {
      let change = await this.UPDATE_DISPATCH({ id: id, producingId: producingId, versionId: versionId, processList: data })
      if (!change) {
        this.editable = true
        this.edit_title = '保存'
      } else {
        this.$alert('变更成功！', '操作成功', {
          confirmButtonText: '确定',
          type: 'success'
        })
      }
    }
  }

  //生成二维码
  async qr(id, dispatchNumber) {
    let result = await this.QRCODE_DISPATCH({ dispatchFormId: id })
    // this.$refs.qr.open(id, dispatchNumber)
  }
  async save() {
    let result
    if (this.pv) {
      this.bb.producingId = this.selectId
      // this.bb.versionId = this.processDetail.versionId
      //  console.log('add', this.addproduct)
      let ee = this.changeData(this.addproduct)
      // this.deleteTid(this.addproduct)
      if (ee) {
        result = await this.CREATE_DISPATCH({ ...this.bb, processList: this.processList })
        //  console.log('提交',result)
        if (result) {
          this.visible = false
        } else {
          this.$alert('提交失败！', '操作失败', {
            confirmButtonText: '确定',
            type: 'warning'
          })
        }
      }
    }
  }

  //加工合并行
  merge({ row, column, rowIndex, columnIndex }) {
    //  console.log(row,row.equipment)

    if (!row.sequenceNumber) {
      if (columnIndex === 1) {
        return [1, 3]
      } else if (columnIndex === 2) {
        return [0, 0]
      } else if (columnIndex === 3) {
        return [0, 0]
      }
    }
  }

  //生产随机数
  random(lower, upper) {
    return Math.floor(Math.random() * (upper - lower)) + lower
  }
  //变更选择
  Selection(sixSelect: any) {
    if (sixSelect.length == 1) {
      //   console.log(sixSelect[0])
      if (sixSelect[0].workerId) {
        this.disable = false
        //this.expList[0].id = sixSelect[0].id
        // this.change = sixSelect[0]
        //判断是否需要展示单双机 取消
        /*
        for (let i = 0; i < this.product.length; i++) {
          let ts = this.product[i].single
   
          for (let j = 0; j < this.product[i].children.length; j++) {
  
            let c = this.product[i].children
            if (c[j].children.length) {
         
              for (let z = 0; z < c[j].children.length; z++) {
              
                let w = c[j].children[z]
                if (w.workerId == sixSelect[0].workerId) {
              
                  if (ts != w.single) {
                    this.singleShow = false
                  }
                }
              }
            }
          }
        }
        */
      }
      if (sixSelect[0].state == '单双机审核') {
        this.singleShow = false
      }
    } else {
      // this.editable = false
      this.edit_title = '变更'
      this.disable = true
      this.singleShow = true
      //  this.sixId = 0
    }
  }
  //添加设备
  addRow() {}
  //指派人 新增 删除
  addRow2() {
    const addPerson = {
      tid: 0,
      workerId: '',
      workerName: '工人A',
      number: ''
    }

    addPerson.tid = ++this.tid

    for (let i = 0; i < this.addproduct.length; i++) {
      for (let j = 0; j < this.addproduct[i].children.length; j++) {
        if (this.addproduct[i].children[j].tid == this.Tid) {
          let w = this.addproduct[i].children
          // console.log('shebeicehng', w[j])
          this.$refs.articleTable.clearSelection()
          return w[j].children.push(addPerson)

          //  this.$set(w[j].children,w[j].children.length,addPerson)
        }
      }
    }

    //  console.log(this.addproduct)
  }
  //删除指派人提示
  deleteRow(tid, rows) {
    this.$alert('您确定删除本记录？', '错误提示', {
      confirmButtonText: '确定',
      type: 'error',
      callback: action => {
        if (action === 'confirm') {
          this.$confirm('此操作将永久删除该数据, 是否继续?', '操作提示', {
            cancelButtonText: '取消',
            confirmButtonText: '确定',
            type: 'warning'
          })

            .then(() => {
              let z = this.deleteData(tid, rows)
              if (z) {
                //  console.log('chengg')
                this.$refs.articleTable.clearSelection()
              }
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              })
            })
        }
      }
    })
  }
  //删除指派人
  deleteData(tid, rows) {
    // console.log('index' + index)
    for (let i = 0; i < rows.length; i++) {
      if (rows[i].tid == tid) {
        this.$alert('该行是工艺设计，不可删除', '错误提示', {
          confirmButtonText: '确定',
          type: 'error'
        })
        break
      } else {
        for (let j = 0; j < rows[i].children.length; j++) {
          let e = rows[i].children //设备层
          if (e[j].tid == tid) {
            this.$alert('该行是工艺设计，不可删除', '错误提示', {
              confirmButtonText: '确定',
              type: 'error'
            })
            break
          } else {
            for (let z = 0; z < e[j].children.length; z++) {
              if (e[j].children[z].tid == tid) {
                e[j].children.splice(z, 1) //删除工人
                // this.addSelection({ tid: 1 })

                this.$nextTick(() => {
                  this.addproduct.map(v => {
                    this.$refs.articleTable.toggleRowSelection(v, true)
                  })
                })
                return true
              }
            }
          }
        }
      }
    }
  }

  addSelection(addselct: any) {
    if (addselct.length == 1) {
      //  console.log('xuanz',selection[0])
      if (addselct[0].equipment) {
        this.addPerson = false
        this.Tid = addselct[0].tid
      } else if (addselct[0].department == '加工') {
        this.addPerson = true
        this.addEquipment = false
      }
    } else {
      this.addPerson = true
      this.addEquipment = true
    }
  }
}
</script>

<style lang="scss" scoped>
// .el-dialog__wrapper {
//   overflow: hidden;
//   .el-dialog {
//     height: 90vh;
//     margin-top: 5vh !important;
//     display: flex;
//     flex-direction: column;
//     .el-dialog__body {
//       flex: 1;
//       // height: 450px;
//       overflow: auto;
//       // .information {
//       //   // margin-top: 20px;
//       // }
//       .input1 {
//         height: 30px;
//         line-height: 30px;
//         padding: 0 12px !important;
//         border-radius: 4px;
//         border: 1px solid #dcdfe6;
//         width: 100%;
//         outline: none;
//       }
//       .el-input__inner {
//         // background-color: #fff;
//         border-color: #e4e7ed;
//         color: #000;
//         // cursor: text;
//       }
//     }
//     .el-dialog__footer {
//       border-top: 1px solid #eee;
//       padding: 10px 20px;
//       background: #fefefe;
//     }
//     .custom-table {
//       // 取消表格下边线
//       tbody tr:last-child td {
//         border-bottom: none !important;
//       }
//     }
//   }
// }

// .order {
//   float: right;
//   // display: inline;
//   border: 1px solid #ccc;
//   background: #fafafa;
//   margin-left: 10px;
//   border-radius: 15px;
//   .paigong_title {
//     width: 170px;

//     color: #000;
//     height: 60px;
//     line-height: 20px;
//     text-align: center;
//     .text {
//       font-size: 14px;
//       font-weight: bold;
//       margin: 0 5px;
//     }
//   }
// }
// .d {
//   display: none;
// }
// .d2 {
//   display: block;
//   margin-bottom: 20px;
// }
// //通知单滚动
// .distribute-box {
//   // width: 95%;
//   display: -webkit-box;
//   overflow-x: auto;
//   /*适应苹果*/
//   -webkit-overflow-scrolling: touch;
// }

// .distribute-item {
//   height: 70px;
// }

// /*隐藏掉滚动条*/
// .distribute-box::-webkit-scrollbar {
//   display: none;
// }
</style>